package com.mercury.design.staregy.factory;

import com.mercury.design.staregy.ApiStrategy;
import com.mercury.design.staregy.EmptyApiStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mercury
 * @date 2021/1/28 2:59 下午
 */
@Component
public class ApiStrategyFactory implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static final Map<String, ApiStrategy> API_STRATEGY_FACTORY_MAP = new HashMap<>();

    private static final ApiStrategy NON_HTTP_METHOD_STRATEGY = new EmptyApiStrategy();

    public static ApiStrategy getApiStrategy(String msgType) {
        ApiStrategy apiStrategy = API_STRATEGY_FACTORY_MAP.get(msgType);
        return apiStrategy == null ? NON_HTTP_METHOD_STRATEGY : apiStrategy;
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, ApiStrategy> map = applicationContext.getBeansOfType(ApiStrategy.class);
        map.forEach((key, value) -> API_STRATEGY_FACTORY_MAP.put(value.fetchKey(), value));
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
